<template>
  <a-modal
    title="新建部门"
    centered
    force-render
    ok-text="确认"
    cancel-text="取消"
    :mask-closable="false"
    :open="props.open"
    width="416"
    :confirm-loading="loading"
    @ok="onOk"
    @cancel="props.onCancel"
  >
    <!-- 加载中 -->
    <div v-if="init" class="float-left text-center mt-30">
      <a-spin />
    </div>

    <!-- 表单 -->
    <div v-else class="float-left mt-24">
      <a-form
        ref="formRef"
        :model="formModel"
        name="department-create"
        @finish="onFinish"
        @finishFailed="onFinishFailed"
        :label-col="{ span: 8 }"
        :wrapper-col="{ span: 16 }"
        autocomplete="off"
      >
        <a-form-item
          label="所属上级"
          name="parent_id"
          :rules="[{ required: true, message: '请选择所属上级!' }]"
        >
          <a-cascader
            v-model:value="formModel.parent_id"
            :options="departments"
            allow-clear
            placeholder="请选择所属上级"
            change-on-select
            :display-render="displayRender"
            style="width: 200px"
            @change="handleChange"
          />
        </a-form-item>

        <a-form-item
          label="部门名称"
          name="name"
          :rules="[{ required: true, message: '请输入部门名称!' }]"
        >
          <a-input
            v-model:value="formModel.name"
            allow-clear
            placeholder="请输入部门名称"
            style="width: 200px"
          />
        </a-form-item>
      </a-form>
    </div>
  </a-modal>
</template>

<script setup lang="ts">
import { ref, reactive, watch } from "vue";
import { message } from "ant-design-vue";
import { department } from "@/api";

interface Props {
  open: boolean;
  onCancel: () => void;
}

const props = defineProps<Props>();

const formRef = ref();
const init = ref(true);
const loading = ref(false);

const formModel = reactive({
  name: "",
  parent_id: [] as (number | string)[],
});

const departments = ref<any[]>([]);
const parentId = ref<number>(0);

// 监听弹窗打开
watch(
  () => props.open,
  (val) => {
    if (val) {
      init.value = true;
      formRef.value?.resetFields();
      formModel.name = "";
      formModel.parent_id = [0];
      parentId.value = 0;
      loadDepartments();
    }
  }
);

// 获取部门数据
const loadDepartments = async () => {
  try {
    const res: any = await department.createDepartment();
    const data = res.data.departments;
    let newArr: any[] = [];
    if (JSON.stringify(data) !== "{}") {
      newArr = buildOptions(data, 0);
    }
    newArr.unshift({ label: "作为一级部门", value: 0 });
    departments.value = newArr;
  } catch (e) {
    console.error(e);
  } finally {
    init.value = false;
  }
};

// 构造 cascader options
const buildOptions = (deps: any, id: number) => {
  const arr: any[] = [];
  for (let i = 0; i < (deps[id]?.length || 0); i++) {
    const item = deps[id][i];
    if (!deps[item.id]) {
      arr.push({ label: item.name, value: item.id });
    } else {
      arr.push({
        label: item.name,
        value: item.id,
        children: buildOptions(deps, item.id),
      });
    }
  }
  return arr;
};

// 处理选择变化
const handleChange = (value: any[]) => {
  parentId.value = value?.length ? value[value.length - 1] : 0;
};

// Modal 确认
const onOk = () => {
  formRef.value.validate().then(() => {
    onFinish(formModel);
  }).catch((e: any) => {
    console.log("表单验证失败", e);
  });
};

// 提交
const onFinish = async (values: any) => {
  if (loading.value) return;
  loading.value = true;
  try {
    await department.storeDepartment(values.name, parentId.value || 0, 0);
    message.success("保存成功！");
    props.onCancel();
  } catch (e) {
    console.error(e);
  } finally {
    loading.value = false;
  }
};

const onFinishFailed = (err: any) => {
  console.log("表单校验失败：", err);
};

// 显示最后一级 label
const displayRender = ({ labels }: { labels: string[] }) => {
  return labels.length ? labels[labels.length - 1] : "";
};
</script>

<style scoped>
</style>
